<?php

ini_set('date.timezone','Asia/Shanghai');

include('./mysql.php');

$analytics = new LogAnalytics;

$logPath = 'C:\Users\arvin\Desktop\nginx-1.0.11\nginx-1.0.11\logs\access.log';

$analytics->analytics($logPath);


/**
 *	对日志的分析
 **/
class LogAnalytics
{
	private $fileLog = null;
	private $fileLogPath = null;
	
	/**
	 *	删除该文件
	 **/
	private function delFileLog(){
		//@unlink($this->fileLogPath);
	}
	
	/**
	 *	把数据写入到数据库
	 **/
	private function updateLines($list){
		foreach($list AS $key=>$val){
			insertJoyData($val,intval($key));
		}
	}
	
	/**
	 *	读取文件的1000行
	 **/
	private function read1000Lines(){
		$list = array();
		if($this->fileLog){
			while(!feof($this->fileLog)){
				$list[] = fgets($this->fileLog);
				if(count($list) >= 1000){
					break;
				}
			}
		}
		$this->updateLines($list);//更新数据
	}
	
	/**
	 *	分析日志文件
	 **/
	public function analytics($filename){
		if(file_exists($filename)){
			$this->fileLogPath = $filename;
			$this->fileLog = fopen($this->fileLogPath,'r');
			if($this->fileLog){
				while(!feof($this->fileLog)){
					$this->read1000Lines();
				}
				fclose($this->fileLog);
				$this->delFileLog();
			}else{
				trigger_error('打开文件：'.$this->fileLog.'失败',E_USER_ERROR);
			}
		}
	}
	
	
}


/**
 *	插入的数据
 *	参数：$line String log中的一行
 *		  $size Int    该记录的次数
 **/
function insertJoyData($line,$size = 0){
	if($size > 0 AND strlen($line) > 2){
		$record	= explode(' ',$line);

		$timestamp = strtotime(ltrim($record[3],'[').' +0800');
		$filter = substr(substr($record[6],2),0,-1);
		parse_str($filter);

		$INSERTSQL = sprintf("INSERT IGNORE INTO daylog(`channel`,`time`,`area`,`adid`,`capacity`,`occupation`,`cityid`,`frequency`) VALUES(%s,%d,%d,%d,%d,%d,%d,'%d')",$channel,$timestamp,$area,$aid,$capcity,$occupation,$area,$frequency);

		//$UPDATESQL = sprintf("UPDATE daylog SET total=total+%d WHERE year=%d AND month=%d AND day=%d AND uid=%d AND vid=%d AND domain='%s' AND Ftype='%s'",$size,$year,$month,$day,$uid,$vid,$domain,$Ftype);
		//echo $INSERTSQL."\n";

		
		if($this->mysql->query($INSERTSQL)){
			if($this->mysql->getAffectedRows() == 0){
				if($this->mysql->query($UPDATESQL)){
					return true;
				}
			}
		}
	
	}
	return false;
}

?>